from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import re


class Project(models.Model):
    """项目模型"""
    name = models.CharField(
        max_length=200, 
        verbose_name='项目名称',
        help_text='项目的完整名称'
    )
    description = models.TextField(
        verbose_name='项目描述',
        help_text='详细描述项目内容和目标'
    )
    semester = models.CharField(
        max_length=20, 
        verbose_name='学期',
        help_text='格式: YYYY-YYYY-N (如: 2024-2025-1)',
        validators=[
            RegexValidator(
                regex=r'^\d{4}-\d{4}-[12]$',
                message='学期格式错误，应为: YYYY-YYYY-N (如: 2024-2025-1)'
            )
        ]
    )
    admin_manager = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='教务负责人',
        help_text='负责管理此项目的教务人员'
    )
    budget = models.DecimalField(
        max_digits=10, 
        decimal_places=2, 
        verbose_name='项目经费',
        help_text='项目总经费（单位：元）'
    )
    
    # 新增三个时间字段
    project_start_date = models.DateField(
        null=True, 
        blank=True, 
        verbose_name='立项时间',
        help_text='项目正式立项的日期'
    )
    midterm_check_date = models.DateField(
        null=True, 
        blank=True, 
        verbose_name='中期检查时间',
        help_text='项目中期检查的日期'
    )
    project_end_date = models.DateField(
        null=True, 
        blank=True, 
        verbose_name='结项时间',
        help_text='项目正式结项的日期'
    )
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '项目'
        verbose_name_plural = '项目'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"{self.name} ({self.semester})"
    
    def clean(self):
        """数据验证"""
        super().clean()
        
        # 验证学期格式
        if self.semester:
            if not re.match(r'^\d{4}-\d{4}-[12]$', self.semester):
                raise ValidationError({
                    'semester': '学期格式错误，应为: YYYY-YYYY-N (如: 2024-2025-1)'
                })
            
            # 验证学期年份逻辑
            years = self.semester.split('-')
            if len(years) >= 2:
                try:
                    start_year = int(years[0])
                    end_year = int(years[1])
                    if end_year != start_year + 1:
                        raise ValidationError({
                            'semester': '学期年份不连续，结束年份应为开始年份+1'
                        })
                except ValueError:
                    pass  # 正则已经验证了格式
        
        # 验证经费为正数
        if self.budget and self.budget <= 0:
            raise ValidationError({
                'budget': '项目经费必须大于0'
            })
    
    @property
    def remaining_budget(self):
        """剩余经费"""
        total_subproject_used = sum(
            subproject.used_budget 
            for subproject in self.subproject_set.all()
        )
        return self.budget - total_subproject_used
    
    @property
    def subproject_count(self):
        """子项目数量"""
        return self.subproject_set.count()
    
    @property
    def completed_subproject_count(self):
        """已完成子项目数量"""
        return self.subproject_set.filter(status='completed').count()
    
    def can_add_subproject_budget(self, amount):
        """检查是否可以添加指定金额的子项目"""
        return self.remaining_budget >= amount
    
    def get_semester_display_name(self):
        """获取学期显示名称"""
        if not self.semester:
            return ''
        
        parts = self.semester.split('-')
        if len(parts) == 3:
            return f"{parts[0]}-{parts[1]}学年第{parts[2]}学期"
        return self.semester